<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true">
        <el-form-item label="用户名：">
          <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="keyword ? false : true"
            @click="search"
          >
            搜索
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" @click="addAclUser">添加用户</el-button>
      <el-button
        :disabled="idList.length > 0 ? false : true"
        type="danger"
        @click="batchDeleteUser"
      >
        批量删除
      </el-button>
      <el-table
        border
        style="margin: 10px 0"
        :data="aclUserArr"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column label="id" prop="id"></el-table-column>
        <el-table-column label="用户名字" prop="username"></el-table-column>
        <el-table-column label="用户昵称" prop="name"></el-table-column>
        <el-table-column label="用户角色" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="265px">
          <template #="{ row }">
            <el-button
              type="primary"
              icon="User"
              size="small"
              @click="assignRoles(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="editAclUser(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              icon="Delete"
              size="small"
              @click="removeAclUser(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="getAclUserArr"
        @size-change="changeSize"
      />
    </el-card>
    <el-drawer v-model="drawerAddOrUpdate" @close="closeDrawer">
      <template #header>
        <h4>{{ addAclUserForm.id ? '修改用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :model="addAclUserForm" :rules="rules" ref="rulesFormRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户姓名"
              v-model="addAclUserForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请输入用户昵称"
              v-model="addAclUserForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            v-if="!addAclUserForm.id"
            prop="password"
          >
            <el-input
              placeholder="请输入用户密码"
              v-model="addAclUserForm.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerAddOrUpdate = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawerRole">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input
              placeholder="请输入用户姓名"
              v-model="addAclUserForm.username"
              :disabled="drawerRole"
            ></el-input>
          </el-form-item>
          <el-form-item label="职位列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="userRoles"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="role in allRolesList"
                :key="role.id"
                :label="role.roleName"
                :value="role"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerRole = false">取消</el-button>
          <el-button type="primary" @click="saveRole">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  reqGetAclUser,
  reqAddOrUpdateAclUser,
  reqAllRole,
  reqAssignRole,
  reqDeleteAclUser,
  reqDeleteAclUserById,
} from '@/api/acl/user/index'
import type { AclUser, RolesList } from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import useLayoutSettingStore from '@/store/modules/setting'
let pageNo = ref(1)
let pageSize = ref(5)
let keyword = ref('')
let total = ref(0)
let aclUserArr = ref<AclUser[]>([])
let drawerAddOrUpdate = ref(false)
let addAclUserForm = reactive<AclUser>({
  username: '',
  password: '',
  name: '',
})
const layoutSettingStore = useLayoutSettingStore()
const rulesFormRef = ref()
onMounted(() => {
  getAclUserArr()
})
const getAclUserArr = (pager = 1) => {
  pageNo.value = pager
  reqGetAclUser(pageNo.value, pageSize.value, keyword.value).then((res) => {
    if (res.code == 200) {
      total.value = res.data.total
      aclUserArr.value = res.data.records
    }
  })
}
const search = () => {
  getAclUserArr()
  keyword.value = ''
}
const reset = () => {
  layoutSettingStore.reFresh = !layoutSettingStore.reFresh
}
const changeSize = () => {
  getAclUserArr()
}
const addAclUser = () => {
  Object.assign(addAclUserForm, {
    username: '',
    password: '',
    name: '',
    id: '',
  })
  drawerAddOrUpdate.value = true
}
const saveUser = () => {
  rulesFormRef.value.validate().then(() => {
    reqAddOrUpdateAclUser(addAclUserForm).then((res) => {
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: addAclUserForm.id ? '修改成功' : '添加成功',
        })
        drawerAddOrUpdate.value = false
        // getAclUserArr(addAclUserForm.id ? pageNo.value : 1)
        window.location.reload()
      } else {
        ElMessage({
          type: 'error',
          message: addAclUserForm.id ? '修改失败' : '添加失败',
        })
      }
    })
  })
}
const editAclUser = (row: AclUser) => {
  Object.assign(addAclUserForm, row)
  drawerAddOrUpdate.value = true
}
const validatorUserName = (_rule: any, value: any, callback: any) => {
  if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('用户名字长度至少五位'))
  }
}
const validatorName = (_rule: any, value: any, callback: any) => {
  if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称长度至少五位'))
  }
}
const validatorPassWord = (_rule: any, value: any, callback: any) => {
  if (value.length >= 6) {
    callback()
  } else {
    callback(new Error('用户密码长度至少六位'))
  }
}
const rules = reactive({
  username: [{ required: true, trigger: 'blur', validator: validatorUserName }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassWord }],
})

const closeDrawer = () => {
  rulesFormRef.value.resetFields()
}

let drawerRole = ref(false)
const assignRoles = (row: AclUser) => {
  Object.assign(addAclUserForm, row)
  reqAllRole(row.id as number).then((res) => {
    if (res.code == 200) {
      allRolesList.value = res.data.allRolesList
      userRoles.value = res.data.assignRoles
      drawerRole.value = true
    }
  })
}
const checkAll = ref(false)
const isIndeterminate = ref(true)
const userRoles = ref<RolesList>([])
const allRolesList = ref<RolesList>([])

const handleCheckAllChange = (val: boolean) => {
  userRoles.value = val ? allRolesList.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRolesList.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRolesList.value.length
}

const saveRole = () => {
  reqAssignRole({
    userId: addAclUserForm.id as number,
    roleIdList: userRoles.value.map((item) => item.id),
  }).then((res) => {
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '分配角色成功',
      })
      drawerRole.value = false
      getAclUserArr()
    } else {
    }
  })
}

const batchDeleteUser = () => {
  reqDeleteAclUser(idList.value).then((res) => {
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '批量删除成功',
      })
      getAclUserArr()
    }
  })
}
let idList = ref<number[]>([])
const handleSelectionChange = (val: AclUser[]) => {
  idList.value = val.map((item) => item.id as number)
}
const removeAclUser = (id: number) => {
  reqDeleteAclUserById(id).then((res) => {
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getAclUserArr()
    }
  })
}
</script>
<script lang="ts">
export default {
  name: 'User',
}
</script>
<style lang="scss"></style>
